/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    TouchableWithoutFeedback,
    InteractionManager,
    TouchableHighlight
} from 'react-native';
import { SwipeListView,SwipeRow } from 'react-native-swipe-list-view';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsDetail from '../components/GoodsDetail';
import AddGoods from './AddGoods';
import StorageUser from '../lib/plugins/StorageUser';
import shopService from '../lib/services/shopService';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class GoodsManage extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.rowList = [];
        this.shopId = '';
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource:ds.cloneWithRows(this.rowList),
            modalVisible:false,
            listName:['综合排序','库存排序','价格升序','价格降序'],
            showName:'综合排序',
            token:this.props.navigation.state.params.token,
        };
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                if(data.shopId){
                    $this.shopId = data.shopId;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getGoodsList();
                });              
            }).catch(err=> {
                console.log(err)
            });
    }
    renderModal(){
        return(
            <Modal
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={()=>this.requestClose()}>
                <TouchableWithoutFeedback onPress={()=>this.setState({modalVisible:false})}>
                    <View style={styles.modalBox}>
                        <View style={styles.listBorder}>
                            {this.renderModalList()}
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            </Modal>
            
        )
    }

    renderModalList(){
        return(
            this.state.listName.map((item,i)=>{
                return(
                    <TouchableOpacity key={i} onPress={()=>this.changeName(item,i)}>
                        <View style={styles.listItem}>
                            <Text>{item}</Text>
                        </View>
                    </TouchableOpacity>
                )
            })
            
        )
    }

    render(){
        return (
            <View style={styles.container}>
                {this.renderModal()}
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'商品管理'} 
                    leftPress={()=>this.goBack()}
                    rightText={'+'}
                    rightTextPress={()=>this.goAddGoods()}
                    rightTextStyle={{color:'#fff',fontSize:24}}/>
                <View style={{flexDirection:'row',borderBottomWidth:1,borderBottomColor:'#C8C8CA'}}>
                    <TouchableOpacity onPress={()=>this.showModal()} style={{flex:1}}>
                        <View style={{flexDirection:'row',justifyContent:'center',alignItems:'center',height:40}}>
                            <Text>{this.state.showName}</Text>
                            <Text style={{width:0,height:0,borderTopWidth:5,borderTopColor:'#2F2F46',borderBottomWidth:5,borderBottomColor:'transparent',borderLeftWidth:5,borderLeftColor:'transparent',borderRightWidth:5,borderRightColor:'transparent',marginTop:8,marginLeft:10}}></Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity style={{flex:1}}>
                        <View style={{justifyContent:'center',alignItems:'center',height:40}}>
                            <Text>销量领先</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                <SwipeListView
                    dataSource={this.state.dataSource}
                    enableEmptySections={true}
                    closeOnRowBeginSwipe={true}
                    rightOpenValue={-120} 
                    disableRightSwipe={true}
                    renderRow={(data, secdId, rowId, rowMap) => (
                            
                                <TouchableHighlight underlayColor={'#fff'}  onPress={ ()=> {rowMap[`${secdId}${rowId}`].closeRow()}}>
                                    <View>
                                        <GoodsDetail 
                                            name={data.g_name} 
                                            icon={{uri:'http://peita.oss-cn-beijing.aliyuncs.com/'+data.g_img}} 
                                            imgWidth={80} imgHeight={80} 
                                            goodsNum={data.g_num}
                                            brand={'品牌：'+data.g_cate}
                                            price={data.g_price}
                                            onPress={()=>this.goEditGoods()}/>
                                    </View>
                                </TouchableHighlight>
                            
                    )}
                    renderHiddenRow={ (data, secdId, rowId) => (
                        <View style={{flex:1,flexDirection:'row',justifyContent:'flex-end'}}>
                            <TouchableOpacity style={{backgroundColor:'#ccc',width:60,alignItems:'center',justifyContent:'center'}} onPress={()=>this.goEditGoods(data)}>
                                <View>
                                    <Text style={{color:'#fff',fontSize:16}}>编辑</Text>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={()=>this.deleteGoods(data,rowId)} style={{backgroundColor:'#ff0000',width:60,alignItems:'center',justifyContent:'center'}}>
                                <View>
                                    <Text style={{color:'#fff',fontSize:16}}>删除</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                )}/>
                
            </View>
        )

    }

    goBack(){
        this.props.navigation.goBack();
    }
    goAddGoods(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('AddGoods',{staturs:'添加商品',upData:()=>{
            $this.getGoodsList();
        }})
    }
    goEditGoods(rowData){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('AddGoods',{staturs:'编辑商品',g_id:rowData.g_id,upData:()=>{
            $this.getGoodsList();
        }})

    }
    // 获取商品列表
    getGoodsList(){
        var $this = this;
        shopService.myShopGoodsLists(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                $this.rowList = data.data;
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.rowList),
                })
            }
        },$this.shopId,$this.token)
    }
    // 商品列表排序
    sortGoodsList(type){
        var $this = this;
        if(type==0){
            this.getGoodsList();
        }else{
            shopService.myShopGoodsLists(function(data){
                alert(JSON.stringify(data));
                if(data.code==10000){
                    $this.rowList = data.data;
                    $this.setState({
                        dataSource:$this.state.dataSource.cloneWithRows($this.rowList),
                    })
                }
            },$this.shopId,$this.token,type)
        }
        
    }
    // 删除商品
    deleteGoods(rowData,index){
        var $this = this;
        shopService.shopGoodsIdDel(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                $this.rowList.splice(index,1);
                var list = JSON.parse(JSON.stringify($this.rowList));
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows(list)
                })
            }
        },rowData.g_id,$this.token)
    }
    showModal(){
        this.setState({
            modalVisible:true,
        })
    }

    changeName(name,i){
        this.setState({
            showName:name,
            modalVisible:false
        })
        this.sortGoodsList(i);
    }

    closeModal(){
        this.setState({
            modalVisible:false
        })
    }

    requestClose(){
        this.closeModal()
    }

    goShopCar(){
        const {navigate } = this.props.navigation;
        navigate('ShopCar')
    }

}



const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    modalBox:{
        flex:1,
        backgroundColor:'rgba(3,3,3,.7)',
        justifyContent:'center',
        alignItems:'center',
    },
    listItem:{
        width:3*width/4,
        height:40,
        justifyContent:'center',
        backgroundColor:'#fff',
        paddingLeft:10,
    },
    
});